<template>
  <view>
    <view class="search-box">
      <uni-search-bar placeholder="请输入搜索内容" :radius="100" :cancelButton='none' @input="input"></uni-search-bar>
    </view>

    <!-- 搜索建议列表 -->
    <view class="sugg-list" v-if="searchResults.length!==0">
      <view class="sugg-item" v-for="(item,i) in searchResults" :key="i" @click="gotoDetail(item)">
        <view class="goods-name">
          {{item.goods_name}}
        </view>
        <uni-icons type="right" size="16"></uni-icons>
      </view>
    </view>

    <!-- 搜索历史 -->
    <view class="history-box" v-else>
      <!-- 标题区 -->
      <view class="history-title">
        <text>搜索历史</text>
        <uni-icons type="trash" size="20" @click="clean"></uni-icons>
      </view>
      <!-- 列表区 -->
      <view class="history-list">
        <uni-tag :inverted="true" :text="item" v-for="(item,i) in histories" :key="i"
          @click="gotoGoodsList(item)"></uni-tag>

      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        //延时器的timerId
        timer: null,
        //搜索关键词
        kw: '',
        //搜索结果列表
        searchResults: [],
        // 搜索关键词的历史记录
        historyList: ['a', 'abc', 'abcd']
      };
    },

    onLoad() {
      // 将字符串转数组，并赋值
      this.historyList = JSON.parse(uni.getStorageSync('kw') || '[]')
    },

    methods: {

      //获取关键词
      input(e) {
        clearTimeout(this.timer)
        // console.log(e);
        this.timer = setTimeout(() => {
          // 0.5s内,没有触发新的输入事件,就为搜索关键词赋值
          this.kw = e
          console.log(this.kw);
          this.getSearchList()
        }, 1000)
        console.log(this.timer);
      },

      //获取搜索结果
      async getSearchList() {
        //判断关键字是否为空
        if (this.kw === '') {
          this.searchResults = []
          console.log('this.searchResults为空');
          return
        }
        //发起请求，获取数据
        const {
          data: res
        } = await uni.$http.get('/api/public/v1/goods/qsearch', {
          query: this.kw
        })
        if (res.meta.status !== 200) {
          return uni.$showMsg()
        }
        this.searchResults = res.message
        //保存关键词
        this.saveSearchHistory()
      },

      //跳转到商品详情页面
      gotoDetail(item) {
        console.log(item.goods_id);
        uni.navigateTo({
          url: '/subpkg/goods_detail/goods_detail?goods_id=' + item.goods_id
        })
      },

      //保存关键词的方法
      saveSearchHistory() {
        // this.historyList.push(this.kw)
        //将array数组转化成set对象
        const set = new Set(this.historyList)
        //移除相同的元素
        set.delete(this.kw)
        //添加到末尾
        set.add(this.kw)
        // 重新转化成数组并赋值给历史数组
        this.historyList = Array.from(set)

        //将数组转化成string字符串，再调用uni.setStorageSync(key,value)将搜索历史记录持久化存储到本地
        uni.setStorageSync('kw', JSON.stringify(this.historyList))
      },

      clean() {
        this.historyList = []
        uni.setStorageSync('kw', '[]')
      },

      gotoGoodsList(kw) {
        uni.navigateTo({
          url: '/subpkg/goods_list/goods_list?query=' + kw
        });
      }



    },
    computed: {
      // 由于数组是引用类型,故不要直接基于原数组调用reserve方法,以免修改原来的元素顺序
      // 而是应该新建一个数组,在进行reverse反转
      //和内存无关的数据
      histories() {
        return [...this.historyList].reverse()
      }
    }
  }
</script>

<style lang="scss">
  .search-box {
    position: sticky;
    top: 0;
    z-index: 999;
  }

  .sugg-list {
    background-color: #F8F8F8;
    padding: 0 5px;

    .sugg-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 12px;
      padding: 13px 0;
      border-bottom: 1px solid #efefef;

      .goods-name {
        //文字不允许换行
        white-space: nowrap;
        //溢出部分隐藏
        overflow: hidden;
        //文本溢出后用...代替
        text-overflow: ellipsis;
        margin-right: 3px;
      }
    }
  }

  .history-box {
    padding: 0 5px;

    .history-title {
      display: flex;
      justify-content: space-between;
      height: 40px;
      align-items: center;
      font-size: 13px;
      border-bottom: 1px solid #efefef;
    }

    .history-list {
      display: flex;
      flex-wrap: wrap;

      uni-tag {
        margin-top: 5px;
        margin-right: 5px;
      }
    }
  }
</style>